<?php
require("check_login.php");
require_once("db_api.php");
date_default_timezone_set('Asia/Taipei') ;
function get_day_record($tbl, $epoch, &$retval) {
	$epoch_today = $epoch;
	$epoch_tomorrow = $epoch+86400;
	$ts_min_db = 10000*(int)date('Ymd', $epoch_today);
	$ts_max_db = 10000*(int)date('Ymd', $epoch_tomorrow)-1;
	$result = query_tbl_record($tbl, $ts_min_db, $ts_max_db, $retval);
	if($retval != "OK_OK")
		return null;
	for($i=0;$i<24;$i++) $ret[$i] = 0;
	foreach($result as $key => $value) {
		$tp = $value['tp'];
		$tp = (int)($tp/100);
		$tp = $tp % 100;
		$ret[$tp] = $value['checkins'];
	}
	return $ret;
}
function tbl_record_avg5($tbl,&$retval) { //5 working day average
	$now=time();
	$nDaysBefore = 1;
	$daysCount = 0;
	while($daysCount <5) {
		if(date('N',$now - 86400*$nDaysBefore) >5) {//Sat or Sun
			$nDaysBefore++;
		}
		$result = get_day_record($tbl,$now - 86400*$nDaysBefore, $retval);
		if($retval != "OK_OK") {
			echo "error $retval \n";
			break;
		}
		$array[$nDaysBefore-1] = $result;
		$nDaysBefore ++;
		$daysCount++;
	}
	if($daysCount != 5)
		return "nDaysBefore=$nDaysBefore, daysCount=$daysCount\n";

	for($i=0;$i<24;$i++) {
		$t = 0;
		for($j=0;$j<5;$j++) {
			$t +=  $array[$j][$i];
		}
		$t/= 5;
		$output[$i] = $t;
	}
	return $output;

}
function tbl_record_avg20($tbl) { // 20 working day average
}
function tbl_record_avgwe($tbl) { //1month weekend average
}

$result = tbl_record_avg5("sun_moon_lake", $retval);
if($retval != "OK_OK")
	echo $result;


?>
